package com.api.syh56.shengyunhui.util;

import com.alibaba.fastjson.JSONObject;
import com.api.syh56.shengyunhui.exception.BaseException;
import com.api.syh56.shengyunhui.properties.WechatProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.HashMap;
import java.util.Map;

@Component
public class CodeToOidUtil {

    @Autowired
    private WechatProperties wechatProperties;

    @Autowired
    private RestTemplate restTemplate;
    /**
     * 使用微信登录code获取openid
     * @param code 微信登录返回的code
     * @return 包含openid的Map
     * @throws Exception 抛出运行时异常以处理可能的错误
     */
    public  Map<String, String> getOpenIdByCode(String code){


        String url = UriComponentsBuilder.fromHttpUrl(wechatProperties.getUrl())
                .queryParam("appid", wechatProperties.getAppid())
                .queryParam("secret", wechatProperties.getSecret())
                .queryParam("js_code", code)
                .queryParam("grant_type", "authorization_code")
                .toUriString();

        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

        if (response.getStatusCode() == HttpStatus.OK) {
            String body = response.getBody();
            Map<String, String> result = new HashMap<>();

                JSONObject jsonObject = JSONObject.parseObject(body);
                String errcode = jsonObject.getString("errcode");
                if (errcode != null && !errcode.equals("0")) { // 通常errcode为0表示成功
                    throw new BaseException("微信登录失败，错误码：" + errcode);
                }
                String openid = jsonObject.getString("openid");
                result.put("openid", openid); // 注意：去掉冒号
                return result;

        } else {
            throw new BaseException("微信登录失败，状态码：" + response.getStatusCode());
        }
    }

}
